<?php
/**
 * User: hjd-yao
 * Date: 2019/7/15
 * Time: 15:18
 */

namespace Shop\Http\Controllers\Pc;


use App\Helpers\SelfResponse;
use App\Models\Shop\OrderGoodsModel;
use App\Models\Shop\OrderModel;
use App\Models\Shop\ShopCartModel;
use App\Models\Shop\ShopGoodsModel;
use App\Models\Shop\UserAddressModel;
use Carbon\Carbon;
use function Couchbase\basicEncoderV1;
use DC\UserCenter\Models\UserAuthModel;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Http\Request;
use Shop\Http\Controllers\BaseController;
use Shop\Http\Controllers\Traits\OrderTrait;
use App\Models\Shop\OrderPaymentModel;

class OrderController extends BaseController
{
    use OrderTrait;
    public function buyNow(Request $request, $goods_id)
    {
        $user_id = $request->input('user_id');
        $buy_num = $request->input('number',1);
        $specs = $request->input('goods_specs');
        $goods = ShopGoodsModel::where('goods_id',$goods_id)->where('status',1)->limit(1)->get();
        $zone = 0;
        $total = 0;
        $post_cost = 0;
        $agent_cost = 0;
        foreach ($goods as $val){
            $zone = $val->goods_zone;
            $total += $val->price*$buy_num;
            $agent_cost +=$val->agent_price*$buy_num;
        }

        $this->getPostAddr($user_id);

        return $this->view('order.buy',[
            'goods'=>$goods,
            'buy_num'=>[$goods_id=>$buy_num],
            'specs'=>[$goods_id=>$specs],
            'total'=>$total,
            'post_cost'=>$post_cost,
            'agent_cost'=>$agent_cost,
            'zone'=>$zone,
        ]);
    }

    public function buyCart(Request $request,$zone=1)
    {
        $user_id = $request->input('user_id');
        $cart_id = array_filter(str2arr($request->input('cart_id')));
        if(!$cart_id){
            return SelfResponse::error('请选择结算商品！');
        }

        $carts = ShopCartModel::with('goods')->where('user_id',$user_id)->where('goods_zone',$zone)->whereIn('id',$cart_id)->get();

        $total = 0;
        $post_cost = 0;
        $agent_cost = 0;
        $buy_num = [];
        $specs = [];
        $goods = [];
        $cart_ids = [];
        $goods_ids = [];
        foreach ($carts as $item){

            if($item->goods_zone !=$zone){
                continue;
            }
            $goods_ids[] = $item->goods_id;
            $total += $item->goods->price*$item->num;
            $agent_cost+=$item->goods->agent_price*$item->num;
            $buy_num[$item->goods_id] = $item->num;
            $specs[$item->goods_id] = $item->goods_specs;
            $cart_ids[] = $item->id;
            $goods[] = $item->goods;
        }

        $this->getPostAddr($user_id);
        return $this->view('order.buy',[
            'goods'=>$goods,
            'buy_num'=>$buy_num,
            'specs'=>$specs,
            'total'=>$total,
            'post_cost'=>$post_cost,
            'agent_cost'=>$agent_cost,
            'cart_id'=>arr2str($cart_id),
            'zone'=>$zone,
        ]);
    }


    public function createOrder(Request $request,$zone=1)
    {
        if($request->isMethod('post')){
            $user_id = $request->input('user_id');
            $remark = $request->post('remark');
            $address = $request->post('address');
            $goods_ids = array_filter(str2arr($request->post('goods_id')));
            $cart_id = array_filter(str2arr($request->post('cart_id',0)));

            $goods_specs= $request->post('specs');
            $buy_number = $request->post('number');

            if(!$goods_ids){
                return SelfResponse::error('请选择购买商品');
            }

            $address = UserAddressModel::where('user_id',$user_id)->find($address);
            if(!$address){
                return SelfResponse::error('请选择收货地址');
            }

            $order_id = OrderModel::init()->createOrder($user_id,$address->toArray(),$remark,$zone);
            if(!$order_id){
                return redirect()->back();
            }

            switch ($zone){
                case '1':
                    $pay_type = 101;break;
                case '2':
                    $pay_type = 102;break;
                case '3':
                    $pay_type = 104;break;
                case '4':
                    $pay_type = 105;break;
                default:
                    $pay_type = 101;break;
            }
            if($zone == 2){
                $shop_rate = json_decode(get_rule('pingji_award'))*0.1;
            }else{
                $shop_rate = 1;
            }

            $goods_cost = 0; //商品话费
            $post_cost = 0;//邮费
            $xf_points = 0;
            $agent_price = 0;
            foreach ($goods_ids as $goods_id){
                $goods_info = ShopGoodsModel::find($goods_id);
                $number = $buy_number[$goods_id]>0?$buy_number[$goods_id]:1;
                $spec = $goods_specs[$goods_id];
                $goods_cost += $goods_info->price*$number*$shop_rate;

                $agent_price += $goods_info->agent_price*$number * $shop_rate ;
                OrderGoodsModel::init()->createOrderGoods($order_id,$goods_info->toArray(),$spec,$number,$zone);
            }

            $total_cost = $goods_cost+$post_cost+$agent_price;//应支付
            $pay_price = $total_cost-$xf_points;
            $res = OrderModel::where('order_id',$order_id)->update([
                'goods_price'=>$goods_cost,
                'total_price'=>$total_cost,
                'post_cost'=>$post_cost,
                'pay_price'=>$pay_price,
                'pay_xf_points'=>$agent_price,
                'pay_type'=>$pay_type
            ]);

            if(!$res){
                OrderModel::where('order_id',$order_id)->delete();
                OrderGoodsModel::where('order_id',$order_id)->delete();
                return redirect()->back();
            }
            $order = OrderModel::find($order_id);

            $orderPayment = new OrderPaymentModel();
            if($pay_type == 105){
                $pay_price_money =  $agent_price ;
            }else{
                $pay_price_money = $pay_price ;
            }
            $orderPayment->createPayment(0, $order->order_sn, '', "在线支付订单", $pay_price_money, 1, $order_id);

            if($cart_id){//清空购物车中的选中产品
                ShopCartModel::where('user_id',$user_id)->whereIn('id',$cart_id)->delete();
            }
            return redirect()->route('f_Pc_Order_orderPay',['order_sn'=>$order->order_sn]);
        }else{
            return redirect()->back();
        }
    }

    public function orderPay(Request $request, $order_sn)
    {
        $user_id = $request->input('user_id');
        if($request->isMethod('post')){
            $order = new OrderModel();
            $pay_type = $request->input('zhifu');
            $pay_pwd = $request->input('pay_pwd');
            if($pay_pwd == '' || empty($pay_pwd)){
                return SelfResponse::error('支付密码不能为空');
            }
            if(! UserAuthModel::init()->checkSafePwd($pay_pwd,$user_id)){
                return SelfResponse::error('支付密码输入错误');
            }
            $orderinfo = OrderModel::where('order_sn',$order_sn)->first();
            if($order->payPcOrder($orderinfo->order_id,$user_id,$pay_type)){
                OrderGoodsModel::init()->incrementSales($orderinfo->order_id);
                return SelfResponse::success('支付成功','f_Pc_Order_orderList');
            }
            return SelfResponse::error($order->getErrorMsg('支付失败'),'f_Pc_Order_orderList');
        }else{
            $order = OrderModel::where('order_sn',$order_sn)->first();
            $order_goods = OrderGoodsModel::where('order_id',$order->order_id)->select(['goods_name','number','goods_spec'])->get();
            return $this->pcRender('order.pay',[
                'order'=>$order,
                'order_goods'=>$order_goods,
                'zone'=>$order->goods_zone,
                'pay_type'=>$order->pay_type,
                'pay_money'=>$order->pay_price,
                'order_sn'=>$order_sn,
                'wallet'=>UserWalletModel::find($user_id),
            ]);
        }
    }

    public function orderList(Request $request)
    {
        $user_id = $request->input('user_id');
        $status = $request->input('status',false);

        $goodsModel = OrderModel::with(['goods'])->where('uid',$user_id);
        if($status !== false){
            $goodsModel->where('status',$status);
        }

        $list = $goodsModel->paginate($this->perNum(30));
        return $this->pcRender('order.list',[
            'list'=>$list,
            'status'=>$status,
        ]);
    }



    public function delete(Request $request,$order_sn)
    {
        $user_id = $request->input('user_id');
        $order = OrderModel::where('status',0)->where('uid',$user_id)->where('order_sn',$order_sn)->first();
        if(!$order){
            return SelfResponse::error('订单不存在');
        }

        if($order->delete()){
            return SelfResponse::success('删除成功','f_Pc_Order_orderList');
        }

        return SelfResponse::error('删除失败功');
    }

    public function confirmOrder(Request $request,$order_sn)
    {
        $user_id = $request->input('user_id');
        $order = OrderModel::where('status',2)->where('uid',$user_id)->where('order_sn',$order_sn)->first();
        if(!$order){
            return SelfResponse::error('订单不存在');
        }
        $order->status = 3;
        $order->signed_at = Carbon::now()->timestamp;
        if($order->save()){
            return SelfResponse::success('确认成功','f_Pc_Order_orderList');
        }

        return SelfResponse::error('确认失败');
    }

    public function cancel(Request $request,$order_sn)
    {
        $user_id = $request->input('user_id');

        $order = OrderModel::where('status',0)->where('uid',$user_id)->where('order_sn',$order_sn)->first();
        if(!$order){
            return SelfResponse::error('订单不存在');
        }
        $order->status = 5;
        $order->signed_at = Carbon::now()->timestamp;
        if($order->save()){
            return SelfResponse::success('取消成功','f_Pc_Order_orderList');
        }

        return SelfResponse::error('取消失败');
    }

    /**
     * @title 订单详情
     * @param $order_id
     * @return View
     */
    public function detailOrder(Request $request)
    {
        $user_id = $request->input('user_id');
        $order_id = $request->input('order_id');
        $info = OrderModel::with('goods')->where('uid',$user_id)->find($order_id);

        if(!$info){
            return redirect()->route('f_Pc_Order_orderList');
        }


        return $this->pcRender('order.order_detail',[
            'info'=>$info
        ]);
    }
}